<template>
   <div class="user-container">
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        
        <el-card class="box-card">
            <el-row :gutter="20">
                  <el-col :span="8">
                      <!-- 搜索 -->
                    <el-input  v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                  </el-col>
                  <!-- 添加用户 -->
                  <el-col :span="4">
                   <el-button type="primary" @click="dialogVisible = true"> 添加用户</el-button>
                  </el-col>

              
           </el-row>
        </el-card>

        <!-- 用户列表 -->
        <el-table :data="userList" style="width: 100%" border stripe>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="username" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="180">
            </el-table-column>
            <el-table-column prop="mobile" label="电话" width="180">
            </el-table-column>
            <el-table-column prop="role_name" label="角色" width="180">
            </el-table-column>
            <!-- 状态按钮渲染 -->
            <el-table-column  label="状态" width="180">
                <template slot-scope="scope"> 
                    <!-- {{scope.row.mg_state}} 拿到这一行的数据-->
                    <el-switch v-model="scope.row.mg_state"  active-color="#13ce66" inactive-color="#ff4949"  @change="userStateChange(scope.row)" >  </el-switch>
                </template>
            </el-table-column>
            <!-- 表格操作区域 -->
            <el-table-column prop=" " label="操作" width="300" >
                <template slot-scope="scope">
                    <!-- 编辑用户按钮 -->
                   <el-button type="primary" size="small"  icon="el-icon-edit" @click="editUser(scope.row.id)"> </el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteUser(scope.row.id)"> </el-button>
                    <!-- 角色分配按钮 -->
                    <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable='false'>
                        <el-button type="success" size="small" icon="el-icon-s-tools" @click="setRoleDialog(scope.row)"> </el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <!-- 编辑用户对话框 -->
       <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%" @close = 'editDialogClose'>
        <!-- 内容主体区域 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                        <!-- 用户名 -->
                <el-form-item label="用户名" >
                      <el-input  v-model="editForm.username" disabled prefix-icon='el-icon-user-solid'></el-input>
                </el-form-item>
                        <!-- 邮箱 -->
                <el-form-item  prop="email" label="邮箱" >         
                     <el-input v-model="editForm.email" clearable  prefix-icon='el-icon-s-comment'></el-input>
                </el-form-item>
                        <!-- 电话 -->
                <el-form-item label="电话" prop="mobile">
                      <el-input  v-model.number="editForm.mobile" oninput="value=value.replace(/[^\d]/g,'')"
                        clearable  prefix-icon='el-icon-phone'></el-input>
                </el-form-item>
            </el-form>
            
        <!-- 内容底部区域 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 添加用户对话框 -->
    <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%">
        <!-- 内容主体区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
            <!-- 用户名 -->
            <el-form-item label="用户名" prop="username">
                <el-input  v-model="addForm.username" clearable prefix-icon='el-icon-user-solid'></el-input>
            </el-form-item>
            <!-- 密码 -->
                <el-form-item label="密码" prop="password">
                <el-input  v-model="addForm.password" show-password  prefix-icon='el-icon-info'></el-input>
            </el-form-item>
            <!-- 邮箱 -->
                <el-form-item
                        prop="email"
                        label="邮箱"
                >         
            <el-input v-model="addForm.email" clearable  prefix-icon='el-icon-s-comment'></el-input>
        </el-form-item>
            <!-- 电话 -->
            <el-form-item label="电话" prop="mobile">
                <el-input  v-model="addForm.mobile" oninput="value=value.replace(/[^\d]/g,'')"
                 clearable  prefix-icon='el-icon-phone'></el-input>
            </el-form-item>
        </el-form>
            
        <!-- 内容底部区域 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
     <el-dialog
            title="分配角色"  :visible.sync="setRoleDialogVisible"  width="50%" @close = 'setRoleDialogClosed'>
            <!-- 对话框主体 -->
            <el-row class="usertag" >当前用户名: <el-tag size="small">{{userInfo.username}}</el-tag></el-row>
            <el-row>当前角色名: <el-tag size="small" type="success" >{{userInfo.role_name}}</el-tag></el-row>
            <!--select组件  -->
            <el-select v-model="selectRoleId" placeholder="请选择">
                <el-option v-for="item in roleList" :key="item.id"  :label="item.roleName" :value="item.id">
                </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRole()">确 定</el-button>
            </span>
        </el-dialog>
    <!-- 分页 -->
    <div class="block">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2 , 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total" background>
            </el-pagination>
        </div>
   </div>
</template>


<script>
export default {
    data(){
            // 自定义验证规则
        //     var  checkEmail = (rule, value, callback) =>{
        //         if (!value) {
        //             return callback(new Error('邮箱不能为空'));
        //         }
        //         const regEmail =/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        //         if (regEmail.test(value)) {
        //               callback();
        //         } else {
        //                callback(new Error('请输入合法邮箱'));
        //         }
        //   };
        //     var  checkMobile = (rule, value, callback) =>{
        //         if (!value) {
        //             return callback(new Error('手机号不能为空'));
        //         }
        //         const regMobile =/^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
        //         if (regMobile.test(value)) {
        //               callback();
        //         } else {
        //                callback(new Error('请输入正规手机号'));
        //         }
        //   };
          return{
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:5
            },
            userList:[],
            total:0,
            // 控制对话框显示与隐藏
            dialogVisible:false,
            editDialogVisible:false,
            setRoleDialogVisible:false,
            //分配角色当前行数据
            userInfo:{},
            roleList:[],
            selectRoleId:'',
            // 添加用户表单数据
            addForm:{
                username:'',
                password:'',
                email: '',
                mobile:''
            },
            editForm:{
                username:'',
                email: '',
                mobile:''
            },
            addFormRules:{
                username:[
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                 email:[
                     { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                     { validator: this.checkEmail, trigger: 'blur' }
                        
                 ],
                mobile:[
                     { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator:this.checkMobile,trigger:'blur'}
                ]
            },
            editFormRules:{
                 email:[
                     { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                     { validator: this.checkEmail, trigger: 'blur' }
                        
                 ],
                mobile:[
                     { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator:this.checkMobile,trigger:'blur'}
                ]
            }
        }
    },
    created(){
        this.getUserList()
    },
    methods:{
        // 获取用户列表
        async getUserList(){
            const {data : res}  = await  this.$http.get('users',{params:this.queryInfo},)
            
              if(res.meta.status !== 200) return this.$Message.error('获取用户列表失败！')
              this.$Message.success('获取用户列表成功！')
            this.userList = res.data.users;
            this.total = res.data.total;
            this.pagenum = res.data.pagenum
        },
        // 页码大小
        handleSizeChange(newSize){
            this.queryInfo.pagesize = newSize;
            this.getUserList();
        },
        handleCurrentChange(newPage){
            this.queryInfo.pagenum = newPage;
            this.getUserList();
        },
        // 监听开关状态
        async  userStateChange(userinfo){
            
            const {data:res}  = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        
            if(res.meta.status !== 200){
                userinfo.mg_state = !userinfo.mg_state;
                    return this.$Message.error('更新用户状态失败！')
            }
            this.$Message.success('更新用户状态成功')
            },
        // 自定义验证规则 邮箱
        checkEmail(rule, value, callback) {
                if (!value) {
                    return callback(new Error('邮箱不能为空'));
                }
                // const regEmail =/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                const regEmail =/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
                if (regEmail.test(value)) {
                      callback();
                } else {
                       callback(new Error('请输入合法邮箱'));
                }
          },
        // 自定义验证规则 电话
        checkMobile (rule, value, callback) {
                if (!value) {
                    return callback(new Error('手机号不能为空'));
                }
                const regMobile =/^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
                if (regMobile.test(value)) {
                      callback();
                } else {
                       callback(new Error('请输入正规手机号'));
                }
          },
        //添加用户确认按钮处理事件
        addUser(){
            this.$refs.addFormRef.validate( async valid =>{
            if(!valid) return 
            const {data:res} = await this.$http.post('/users',this.addForm);
            
            if(res.meta.status !== 201)  return this.$Message.error('用户添加失败！')
            this.$Message.success('用户添加成功！')
            this.dialogVisible = false;
            this.getUserList();
           })
         },
        //  展示编辑用户对话框
       async editUser(id){
            this.editDialogVisible = true;
            const {data:res} = await this.$http.get(`users/${id}`)
            if(res.meta.status !== 200 ) return this.$Message.error('数据获取失败')
            this.editForm = res.data
        },
        // 关闭弹窗重置表单事件
        editDialogClose(){
            this.$refs.editFormRef.resetFields();
        },
        // 修改用户数据确定按钮事件
        editUserInfo(){
            this.$refs.editFormRef.validate(async valid =>{
                if(!valid) return 
                // console.log(this.editForm);
                const {data: res} = await this.$http.put(`users/${this.editForm.id}`,
                {
                   email: this.editForm.email,
                   mobile: this.editForm.mobile, 
                })
                if(res.meta.status !== 200 ) return this.$Message.error('更新用户信息失败！')
                this.editDialogVisible = false;
                this.getUserList();
                this.$Message.success('更新用户信息成功！')
            })
        },
        // 点击删除按钮
        // 触发弹窗询问
        deleteUser(id){
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then( async () => {
                 const  {data:res} = await this.$http.delete('users/'+id)
                 if(res.meta.status !== 200) return this.$Message.error('删除用户失败！')
                 
                this.$Message({
                    type: 'success',
                    message: '删除用户成功!'
                });
                this.getUserList();
                }).catch(() => {
                this.$Message({
                    type: 'info',
                    message: '已取消删除操作'
                });          
                });
            },
            // 分配角色对话框展开
        async setRoleDialog(userInfo){
            // 获取所有角色列表
            const {data:res} =  await this.$http.get('roles')
            if(res.meta.status !==200 ) return this.$Message.error('角色列表请求失败！')

            this.roleList = res.data;
            this.setRoleDialogVisible = true;
            // 保存需要被分配角色的用户信息
            this.userInfo = userInfo;
        },
        // 分配角色对话框关闭
        setRoleDialogClosed(){
            this.selectRoleId = '';
            this.userInfo = {};
        },
        // 分配角色对话框确定按钮事件
        async allotRole(){
            if(!this.selectRoleId) return this.$Message.info('请选择角色')
            const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
                rid:this.selectRoleId
            })
            if(res.meta.status !== 200) return this.$Message.error('角色分配失败！')
            this.$Message.success('角色分配成功')
                this.setRoleDialogVisible = false;
                this.getUserList();

        }

    }
 
}
</script>

<style lang="less" scoped>
.el-card{
    margin-top:20px;
    box-shadow: 0 0 3px #ddd;
}
.el-table{
    margin-top: 20px;
}
.block{
    margin-top: 20px;
    padding: 0 auto;
    .el-pagination{
       display: flex;
       justify-content: center;
    }
}
.usertag{
    margin-top: -20px;
    margin-bottom: 15px;
}
.el-select{
      margin-top: 10px;
}
</style>